package com.zjt.acnews;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;

import java.io.IOException;
import java.io.InputStream;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <P>Company: </p>
 *
 * @author zhengjianting
 * @time 2018/11/5 0005 下午 2:05
 */
public class ArticleActivity extends AppCompatActivity {

    public static final String Article_URL = "Article_URL";
    private static final String UA = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";
    private WebView mWebView;
    private RelativeLayout mLinearLayout;
    private Button mCloseBtn;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);

        mLinearLayout = findViewById(R.id.progress_layout);
        mWebView = findViewById(R.id.webview);
        mCloseBtn = findViewById(R.id.close_btn);

        mCloseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLinearLayout.setVisibility(View.GONE);
            }
        });
        initWebView();
        initLoadUrl();
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                mLinearLayout.setVisibility(View.GONE);
//            }
//        }, 3500);
    }

    private void initLoadUrl() {
        String url = getIntent().getStringExtra(Article_URL);
        mWebView.loadUrl(url);
    }

    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setUseWideViewPort(true);
        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); //关闭webview中缓存
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(true);
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setBlockNetworkImage(false);
        webSettings.setUserAgentString(UA);
        webSettings.setTextZoom(150);

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setLoadWithOverviewMode(true);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setVerticalScrollbarOverlay(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setHorizontalScrollbarOverlay(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(webSettings.MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }

        mWebView.setWebViewClient(new WebViewClient() {

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                WebResourceResponse resourceResponse = loadLocalCSS(url);
                if (resourceResponse != null) {
                    return resourceResponse;
                }
                return super.shouldInterceptRequest(view, url);
            }

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    String url = request.getUrl().toString();
                    WebResourceResponse resourceResponse = loadLocalCSS(url);
                    if (resourceResponse != null) {
                        return resourceResponse;
                    }
                }
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                view.loadUrl("javascript:(function() { " +
//                        "document.getElementById('header').style.display='none';" +
//                        "document.getElementById('footer').style.display='none';" +
//                        "document.getElementsByClassName('art-title-census')[0].style.display='none';" +
//                        "document.getElementById('article-up').style.display='none';" +
//                        "document.getElementById('up-info').style.display='none';" +
//                        "document.getElementById('up-contributions').style.display='none';" +
                        "document.getElementById('article-operation').style.display='none';" +
//                        "document.getElementById('realate-article').style.display='none';" +
//                        "document.getElementById('bd_tag').style.display='none';" +
//                        "window.JSLoadFinish.onFinish();" +
                        "})()");

                mWebView.setInitialScale(135);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient());
        //mWebView.addJavascriptInterface(new JSLoadFinishInterface(), "JSLoadFinish");
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }

    class JSLoadFinishInterface {
        @JavascriptInterface
        public void onFinish() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mWebView.setInitialScale(135);
                    mLinearLayout.setVisibility(View.GONE);
                }
            });

        }
    }

    private WebResourceResponse loadLocalCSS(String url) {
        WebResourceResponse resourceResponse = null;
        int flag = 0;
        if (url.contains("comm-artical.min.css")) flag = 1;
        if (url.contains("articledetail.min.css")) flag = 2;
        if (flag > 0) {
            InputStream inputStream = null;
            try {
                if (flag == 1) {
                    inputStream = getAssets().open("comm-artical.min.css");
                } else {
                    inputStream = getAssets().open("articledetail.min.css");
                }
                resourceResponse = new WebResourceResponse("text/css", "UTF-8", inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resourceResponse;
    }
}
